package com.example.demo6301.cfg;

import com.example.demo6301.filter.VerifyCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private VerifyCodeFilter verifyCodeFilter;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //在 Spring Security 的配置中，配置验证码过滤器
        http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);


        http
                .authorizeRequests()
                .antMatchers("/","/test",  "/home","/getVerifyCode").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }


    @Value("${sys.login.account}")
    private String account;


    @Value("${sys.login.password}")
    private String pwd;


    @Bean
    @Override
    public UserDetailsService userDetailsService() {
//        UserDetails user =
//                User.withDefaultPasswordEncoder()
//                        .username("user")
//                        .password("password")
//                        .roles("USER")
//                        .build();
        UserDetails user2 =
                User.withDefaultPasswordEncoder()
                        .username(account)
                        .password(pwd)
                        .roles("ADMIN")
                        .build();

//        return new InMemoryUserDetailsManager(user,user2);
        return new InMemoryUserDetailsManager(user2);
    }
}